package com.train.mgr.config.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

@Component
public class RedisLock {

    @Autowired
    private StringRedisTemplate redis;

    /**
     * 尝试获取锁
     * @param key   锁key
     * @param val   唯一value（可用UUID）
     * @param mills 过期毫秒（防止死锁）
     * @return 是否获取成功
     */
    public boolean tryLock(String key, String val, long mills) {
        Boolean ok = redis.opsForValue()
                .setIfAbsent(key, val, mills, TimeUnit.MILLISECONDS);
        return Boolean.TRUE.equals(ok);
    }

    /**
     * 释放锁（仅当value匹配时才删，防止误删）
     */
    public void unlock(String key, String val) {
        String lua =
                "if redis.call('get', KEYS[1]) == ARGV[1] then " +
                        "  return redis.call('del', KEYS[1]) " +
                        "else return 0 end";
        redis.execute(new DefaultRedisScript<>(lua, Long.class),
                Collections.singletonList(key), val);
    }
}
